import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';

export class EnvConfigManager {
  get isProd() {
    return process.env.NODE_ENV === 'production';
  }

  public static get dbTypeList() {
    return ['mysql', 'postgresql', 'sqlite', 'mssql'] as const;
  }

  private _getConfigStr() {
    try {
      const envPathKey = this.isProd ? '.env.production' : '.env';

      const envPath = __dirname.replace(/([\/\\]dist[\/\\]utils)$/, `/${envPathKey}`);
      const envPathContent = readFileSync(envPath, 'utf-8');
      return envPathContent;
    } catch (e) {
      return '';
    }
  }

  public getConfig() {
    const configStr = this._getConfigStr();
    const configObjectEntries = configStr
      .replace(/\r/g, '')
      .split(/\n/)
      .filter(item => !!item.length && !item.startsWith('#'))
      .map(item => item.split('='));

    const configObject: Record<string, string> = Object.fromEntries(configObjectEntries);

    return configObject;
  }
}
